package com.lims.landInfo.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javacommon.base.*;
import javacommon.util.TextTool;

import cn.org.rapid_framework.page.*;

import com.lims.admin.dao.UserDao;
import com.lims.admin.model.User;
import com.lims.landInfo.model.*;
import com.lims.landInfo.dao.*;
import com.lims.landInfo.vo.query.*;

/**
 * @author zzh
 * @version 1.0
 * @since 1.0
 */@Service
@Transactional @SuppressWarnings("unchecked")
public class CorpaffManager extends BaseManager<Corpaff,java.lang.String>{

	private CorpaffDao corpaffDao;
	private UserDao userDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setCorpaffDao(CorpaffDao dao) {
		this.corpaffDao = dao;
	}
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public EntityDao getEntityDao() {
		return this.corpaffDao;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(CorpaffQuery query) {
		return corpaffDao.findPage(query);
	}

	public void saveAll(List list) {
		this.corpaffDao.saveAll(list);
	}
	
	//根据用户ID取出单位，及所有下级单位
	@Transactional(readOnly=true)
	public List findCorpByUserId(String userId,HttpSession session) {
		Object obj2 = session.getAttribute("user");
		User u = obj2 == null ? null : (User)obj2;
		List corpList = new ArrayList(0);
		if(u == null) return corpList;
		if(TextTool.isNull(userId)) return corpList;
		User user = this.userDao.getById(userId);
		Corpaff corpaff = this.corpaffDao.getById(user.getCorpId());
		Object[] obj = new Object[]{corpaff.getCorpno(),corpaff.getName()};
		corpList.add(obj);
		findCorpByParentNo(corpaff.getCorpno(),corpList);
		return corpList;
	}
	
	@Transactional(readOnly=true)
	public List findAllCorp() {
		String hql = "select c.objid,c.name from Corpaff c";
		return this.corpaffDao.findByHQL(hql);
	}
	
	/****递归取得所有下级单位******/
	private void findCorpByParentNo(String parentNo,List list) {
		String hql = "from Corpaff c where c.parentno='"+parentNo+"'";
		List cList = this.corpaffDao.findByHQL(hql);
		if(TextTool.isNotNull(cList)) {
			for (Iterator iterator = cList.iterator(); iterator.hasNext();) {
				Corpaff corp = (Corpaff) iterator.next();
				Object[] obj = new Object[]{corp.getCorpno(),corp.getName()};
				list.add(obj);
				findCorpByParentNo(corp.getCorpno(),list);
			}
		} 
	}
	
}
